package manager.monitoring;

import java.sql.*;

import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.jboss.ejb3.annotation.*;

import manager.backup.LazyPersistedQueue;
import manager.monitoring.ManagerServiceMBean;
import manager.udp.UDPServer;

import exception.GenericException;
@Service(objectName = "servicePOJO:service=ManagerService") 
@Management(ManagerServiceMBean.class)
@Depends("jboss.jca:name=MySqlDS,service=DataSourceBinding")

public class ManagerService implements ManagerServiceMBean {  

	private static UDPServer ust;
	private static LazyPersistedQueue lpq;


	public boolean authUser(String username)  throws GenericException { 
		Connection conn = null; 
		CallableStatement cs1 = null; 
		try { 
			InitialContext ctx = new InitialContext(); 
			DataSource ds = (DataSource)ctx.lookup("java:/MySqlDS"); 
			conn = ds.getConnection(); 
			String sql = "SELECT * FROM Users WHERE username='"+username+"'";
			cs1 =  conn.prepareCall(sql); 
			ResultSet result = cs1.executeQuery();
			return(result.first());
		} 
		catch (Exception exc) { 
			exc.printStackTrace(); 
		} 
		finally { 
			try { 
				cs1.close(); 
				conn.close(); 
			} 
			catch (SQLException e) { 
				e.printStackTrace(); 
			} 
		}
		return false;
	} 



	// Lifecycle methods 
	public void create() throws Exception { 
		lpq = new LazyPersistedQueue();
		ust = new UDPServer(lpq);
		ust.start();
	} 

	public void destroy() {    
		ust.closeSocket();
	}

} 

